<template>
  <el-card class="change-password-card">
    <h2>修改密码</h2>
    <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="120px"
        class="change-password-form"
    >
      <el-form-item label="当前密码" prop="password">
        <el-input
            type="password"
            v-model="form.password"
            placeholder="请输入当前密码"
        ></el-input>
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input
            type="password"
            v-model="form.newPassword"
            placeholder="请输入新密码"
        ></el-input>
      </el-form-item>

      <el-form-item label="确认新密码" prop="newPasswordAgain">
        <el-input
            type="password"
            v-model="form.newPasswordAgain"
            placeholder="请再次输入新密码"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import {ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import userApi from "@/api/UserApi.js";
import router from "@/router/index.js";

// 表单数据
const form = ref({
  password: '',
  newPassword: '',
  newPasswordAgain: '',
});

// 表单验证规则
const rules = {
  password: [
    {required: true, message: '请输入当前密码', trigger: 'blur'},
    {min: 3, message: '当前密码至少3位', trigger: 'blur'},
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 3, message: '新密码至少3位', trigger: 'blur'},
  ],
  newPasswordAgain: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.newPassword) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

// 表单引用
const formRef = ref(null);

// 提交表单
const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用修改密码接口
        const response = await userApi.changePwd(form.value.password, form.value.newPassword, form.value.newPasswordAgain);
        if (response.code === 10000) {
          ElMessage.success('密码修改成功');
          router.push('/user/login')
        } else {
          ElMessage.error(response.msg || '修改密码失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后再试');
        console.error(error);
      }
    } else {
      ElMessage.error('请完善表单内容');
      return false;
    }
  });
};

// 重置表单
const onReset = () => {
  formRef.value.resetFields();
};


</script>

<style scoped>
.change-password-card {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
}

.change-password-form {
  margin-top: 20px;
}
</style>
